﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
using System.Diagnostics;
//using Excel;

namespace graduation_projects
{
    public partial class MainForm : Form
    {
        //public static ArrayList PatientInfo_FrmList = new ArrayList();
        string ygid, ygpwd; //系统用户表的员工id,员工密码
        string ysdm, ksdm; //医生信息表的 医生代码，科室代码

        public string nowpatientblh = "", nowpatientbrxm = "", nowpatientbrid = "", nowpatientbrxb = "", nowpatientbrxz = "", nowpatientbrnl = "", nowpatientgmwy = "";//当前选中病人的信息
        public string nowpatientjzxh = "";//这几个字段一定要初始化，否则为null空时也会报错。
        public string nowpatientghxh = "";
        public int nodecount;//用来表示treeview1的节点数
        public string nowpatientzd = "";//表示当前病人的诊断

        public MainForm(string id, string pwd)
        {
            ygid = id;
            ygpwd = pwd;//密码供修改密码时使用

            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)//显示底部状态栏信息
        {
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.LabAge.Text = "";
            this.LabPatient.Text = "";
            this.LabSex.Text = "";
            this.LabNature.Text = "";
            this.LabGmyw.Text = "";
            nodecount = this.treeView1.Nodes.Count;
            skinEngine1.SkinFile = "MSN.ssk";//设置皮肤
            
            try
            {
                using (SqlConnection conn = new SqlConnection(SQLConnect.get()))
                {
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "select ygxm from system_users where ygdm=@ygdm";
                    cmd.Parameters.AddWithValue("@ygdm", ygid);
                    conn.Open();
                    string name = (string)cmd.ExecuteScalar();
                    LabDoctor.Text = name;
                    LabDate.Text = System.DateTime.Now.ToString();

                    SqlCommand cmd2 = conn.CreateCommand();
                    cmd2.CommandText = "select ysdm.ksdm,ksdm.ksmc from ksdm,ysdm where ksdm.ksdm=ysdm.ksdm and ysdm=@ygid ";//根据员工id找医生的其他信息
                    cmd2.Parameters.AddWithValue("@ygid", ygid);
                    try
                    {
                        SqlDataReader re = cmd2.ExecuteReader();
                        re.Read();
                        ksdm = (string)re["ksdm"];
                        LabRoom.Text = (string)re["ksmc"];

                    }
                    catch
                    {

                    }
                    ysdm = ygid;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void 病人信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form patinfo = new PatientInfo(nowpatientblh);//运行到这里，调用PatientInfo的构造函数
            patinfo.StartPosition = FormStartPosition.Manual;
            patinfo.Location = Cursor.Position;
            patinfo.ShowDialog();//执行showdialog（）,然后执行PatientInfo_Load（）
        }

        private void 药品字典ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form med = new Medicine();
            med.ShowDialog();

        }

        private void 病历书写ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmCaseHistoryWrite chWrite = new FrmCaseHistoryWrite(nowpatientblh, ysdm, ksdm, nowpatientjzxh);
            //chWrite.MdiParent = this;
            //panel2.Controls.Add(chWrite);
            //chWrite.StartPosition = FormStartPosition.Manual;
            //chWrite.Location = Cursor.Position;
            if (nowpatientblh.Trim() == "")
            {
                MessageBox.Show("请先选择病人");
                return;
            }
            chWrite.ShowDialog();
            nowpatientzd = chWrite.nowpatientzd;
        }

        private void 门诊病历查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmCaseHistoryQuery chQuery = new FrmCaseHistoryQuery(ysdm, ksdm);
            //chQuery.MdiParent = this;
            //panel2.Controls.Add(chQuery );
            chQuery.StartPosition = FormStartPosition.Manual;
            chQuery.Location = Cursor.Position;
            chQuery.ShowDialog();
        }

        private void tsBtnCaseHistory_Click(object sender, EventArgs e)
        {

            FrmCaseHistoryWrite chWrite = new FrmCaseHistoryWrite(nowpatientblh, ysdm, ksdm,nowpatientjzxh );
            //chWrite.MdiParent = this;
            //panel2.Controls.Add(chWrite);
            //chWrite.StartPosition = FormStartPosition.Manual;
            //chWrite.Location = Cursor.Position;
            if (nowpatientblh.Trim() == "")
            {
                MessageBox.Show("请先选择病人");
                return;
            }
            chWrite.ShowDialog();
            nowpatientzd = chWrite.nowpatientzd;
        }

        //------------------------------------------------------------------------------------------------------------
        private void tsBtnNext_Click(object sender, EventArgs e)//下一个
        {
            string[] sqllist = new string[2];
            nodecount = this.treeView1.Nodes.Count;
            if (nodecount == 0)//MainForm窗体的Treeview1无节点，可以进行选病人
            {
                try
                {

                    #region//调用存储过程hzdl_GetPriority，取得当前优先级最高即排队序号最小的病人的blh,赋给当前病人病历号

                    using (SqlConnection cn3 = new SqlConnection())
                    {
                        cn3.ConnectionString = SQLConnect.get(); ;
                        try
                        {
                            cn3.Open();
                        }
                        catch
                        {
                            return;
                        }
                        SqlCommand cmdgetpriority = cn3.CreateCommand();
                        cmdgetpriority.CommandText = "hzdl_GetPriority";
                        cmdgetpriority.CommandType = CommandType.StoredProcedure;

                        //声明输入参数
                        SqlParameter inysdm = new SqlParameter("@ysdm", SqlDbType.NVarChar, 50);
                        cmdgetpriority.Parameters.Add(inysdm);
                        inysdm.Value = ysdm;

                        //声明输出参数
                        SqlParameter blh = new SqlParameter("@blh", SqlDbType.NVarChar, 50);//程序报错：属性具有无效大小值0，所以要加这个50，存储过程里的病历号就是nvarchar(50)
                        blh.Direction = ParameterDirection.Output;
                        cmdgetpriority.Parameters.Add(blh);

                        try
                        {
                            cmdgetpriority.ExecuteNonQuery();
                        }
                        catch (Exception excep)
                        {
                            MessageBox.Show(excep.ToString());
                        }

                        nowpatientblh = blh.Value.ToString();
                    }

                    #endregion

                    ////若队列中没有dzzt=0的，则nowpatientblh="",就不需要执行下面的
                    if (nowpatientblh != "")
                    {
                        getPatientInfo.getBaseInfo(nowpatientblh);
                        nowpatientbrid = getPatientInfo.brid;
                        nowpatientbrnl = getPatientInfo.brnl;
                        nowpatientbrxb = getPatientInfo.brxb;
                        nowpatientbrxm = getPatientInfo.brxm;
                        nowpatientbrxz = getPatientInfo.brxz;
                        nowpatientgmwy = getPatientInfo.gmwy;

                        sqllist[0] = "update hzdl set dzzt='3' where blh=" + nowpatientblh+" and ghxh=@ghxh";
                        sqllist[1] = "insert into jzls(jzxh,brxm,blh,brid,ksdm,ysdm,kssj,jzzt,ghxh) values (@jzxh,@brxm,@blh,@brid,@ksdm,@ysdm,@kssj,'1',@ghxh)";

                        updateDataBase(sqllist);//对选出的病人更新数据库 //因为点 下一个选出病人 和 输入病历号选出病人 都要用到这个更新数据库的方法，所以更新数据库写在一个方法里面
                        SelectPatient.patselected = true;
                        createTree();//生成病人数  //因为点 下一个选出病人 和 输入病历号选出病人 都要用到这个生成病人树的方法，所以生成病人树写在一个方法里面

                    }
                }
                catch(Exception exc)
                {
                    MessageBox.Show(exc.ToString());
                }
            }
            else//MainForm窗体的Treeview1有节点，要先处理完节点上的病人，才可以再选病人
            {
                MessageBox.Show("请先处理当前病人！");
            }

        }

        private void tsBtnSelPatient_Click(object sender, EventArgs e)//选病人按钮，打开选病人窗口
        {
            nodecount = this.treeView1.Nodes.Count;//把当前treevi的节点数传给选病人窗体
            SelectPatient selpat = new SelectPatient(ysdm, ksdm, nodecount);
            selpat.StartPosition = FormStartPosition.Manual;
            selpat.Location = Cursor.Position;
            selpat.ShowDialog();

            if (selpat.DialogResult == DialogResult.Cancel && SelectPatient.patselected == true)
            {

                nowpatientblh = SelectPatient.nowpatientblh;
                nowpatientbrxm = SelectPatient.nowpatientbrxm;
                nowpatientbrid = SelectPatient.nowpatientbrid;
                nowpatientbrnl = SelectPatient.nowpatientbrnl;
                nowpatientbrxb = SelectPatient.nowpatientbrxb;
                nowpatientbrxz = SelectPatient.nowpatientbrxz;
                nowpatientgmwy = SelectPatient.nowpatientgmwy;
                nowpatientjzxh = SelectPatient.nowpatientjzxh;
                nowpatientghxh = SelectPatient.nowpatientghxh;

                createTree();

            }

        }

        private void tsTxtCaseHistory_KeyDown(object sender, KeyEventArgs e)//输入病历号，选出病人
        {
            string tempblh = "";
            string[] sqllist = new string[2];

            if (e.KeyCode == Keys.Enter && tsTxtCaseHistory.Text != "")
            {
                using (SqlConnection conn = new SqlConnection(SQLConnect.get()))
                {
                    conn.Open();
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "select blh from hzdl where blh=@blh and dzzt='0'and ysdm=@ysdm and ghsj>=@today ";

                    SqlParameter parysdm = new SqlParameter("@ysdm", SqlDbType.NVarChar);
                    parysdm.Value = ysdm;
                    cmd.Parameters.Add(parysdm);

                    SqlParameter partoday = new SqlParameter("@today", SqlDbType.NVarChar);
                    partoday.Value = System.DateTime.Today.ToString();
                    cmd.Parameters.Add(partoday);


                    SqlParameter partblh = new SqlParameter("@blh", SqlDbType.NVarChar);
                    partblh.Value = tsTxtCaseHistory.Text;
                    cmd.Parameters.Add(partblh);

                    try
                    {
                        tempblh = cmd.ExecuteScalar().ToString();//ExecuteScalar最快速度返回第一行第一列的值
                    }
                    catch
                    {
                        tempblh = "";//如果没有该病历号，或该病历号不符合条件，则置tempblh为空
                    }


                    if (tempblh != "" && treeView1.Nodes.Count == 0) // tempblh不为空，则有符合条件的记录,并且当前没有正在处理的病人，就可以执行下面的代码
                    {
                        nowpatientblh = tempblh;
                        getPatientInfo.getBaseInfo(nowpatientblh);
                        nowpatientbrid = getPatientInfo.brid;
                        nowpatientbrnl = getPatientInfo.brnl;
                        nowpatientbrxb = getPatientInfo.brxb;
                        nowpatientbrxm = getPatientInfo.brxm;
                        nowpatientbrxz = getPatientInfo.brxz;
                        nowpatientgmwy = getPatientInfo.gmwy;

                        sqllist[0] = "update hzdl set dzzt='3' where blh=" + nowpatientblh+" and ghxh=@ghxh";
                        sqllist[1] = "insert into jzls(jzxh,brxm,blh,brid,ksdm,ysdm,kssj,jzzt,ghxh) values (@jzxh,@brxm,@blh,@brid,@ksdm,@ysdm,@kssj,'1',@ghxh)";

                        updateDataBase(sqllist);
                        SelectPatient.patselected = true;
                        createTree();
                        tsTxtCaseHistory.Text = "";//清空输入病历号的框
                        treeView1.Focus();

                    }
                    else if (tempblh != "" && treeView1.Nodes.Count != 0)
                        MessageBox.Show("请先处理当前病人！");
                }

            }
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)//树节点的双击事件
        {
            string str_1;
            if (e.Node.Level != 0)
            {
                str_1 = treeView1.SelectedNode.Parent.Text;
                if (str_1 == "检验单")
                {
                    jyd_win w_jyd_win1 = new jyd_win(nowpatientblh, ysdm, treeView1.SelectedNode.Text, nowpatientjzxh);
                    w_jyd_win1.ShowDialog();

                    if (w_jyd_win1.DialogResult == DialogResult.Cancel && jyd_win.str_sqdh == "")
                    {
                        treeView1.Nodes.Remove(treeView1.SelectedNode);
                    }
                }
                else if (str_1 == "处方单")
                {
                    new cfdmodify(treeView1.SelectedNode.Text).ShowDialog();
                }
            }
        }

        private void tsBtnZanGua_Click(object sender, EventArgs e)//保存暂挂病人
        {
            int parnodeindex = 0;
            bool firlevelnode = false;
            nodecount = treeView1.Nodes.Count;

            if (nodecount == 0)//当前没有病人被选中
                return;

            else//当前有病人被选中
            {
                #region//判断是否第一层节点
                try
                {

                    parnodeindex = treeView1.SelectedNode.Parent.Index;

                }
                catch
                {
                    firlevelnode = true;//执行到这里，即当前选中节点无父节点，即当前选中节点为第一层的节点，方可暂挂病人。包括主窗体一打开，就点暂挂的情况
                }
                #endregion

                if (firlevelnode == true)//若选中节点为第一层节点，执行这里
                {
                    if (nowpatientblh != "")
                    {
                        using (SqlConnection cn = new SqlConnection(SQLConnect.get()))
                        {

                            #region//-------尝试打开连接---------------------------------------
                            try
                            {
                                cn.Open();
                            }
                            catch
                            {
                                return;
                            }
                            #endregion//--------------------------------------------------------------------------

                            #region//---尝试提交事务，更新jzls表，保存暂挂病人------------------------------------
                            using (SqlTransaction tran = cn.BeginTransaction(IsolationLevel.RepeatableRead))
                            {
                                try
                                {
                                    using (SqlCommand cmd = cn.CreateCommand())
                                    {
                                        cmd.CommandTimeout = 3;
                                        cmd.Transaction = tran;
                                        cmd.CommandText = "update jzls set jzzt='2' where blh=@blh and ghxh=@ghxh";

                                        SqlParameter blh = new SqlParameter("@blh", SqlDbType.NVarChar,50);
                                        cmd.Parameters.AddWithValue("@blh", nowpatientblh);

                                        SqlParameter ghxh= new SqlParameter("@ghxh", SqlDbType.NVarChar,50);
                                        cmd.Parameters.AddWithValue("@ghxh", nowpatientghxh);

                                        try
                                        {
                                            cmd.ExecuteNonQuery();
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageBox.Show(ex.ToString());
                                        }
                                    }

                                    tran.Commit();//执行事务
                                }

                                catch (Exception ex)
                                {
                                    tran.Rollback();//有错就回滚
                                    MessageBox.Show(ex.ToString());
                                }
                            }
                            #endregion//-------------------------------------------------------------------

                        }

                        treeView1.SelectedNode.Remove();//暂挂病人，删去该选中节点及其子节点
                        nowpatientblh = ""; nowpatientbrxm = ""; nowpatientbrid = ""; nowpatientbrxb = ""; nowpatientbrxz = ""; nowpatientbrnl = ""; nowpatientgmwy = "";//当前选中病人的信息
                        nowpatientjzxh = "";//清空当前选中病人的信息
                        nowpatientghxh = "";
                        LabPatient.Text = ""; LabSex.Text = ""; LabAge.Text = ""; LabNature.Text = ""; LabGmyw.Text = "";//清空导航栏信息
                    }

                }
                else//若选中节点不是第一层节点，什么都不做
                {

                }
            }
        }

        private void tsBtnEnd_Click(object sender, EventArgs e)//保存已就诊结束病人
        {

            int parnodeindex = 0;
            bool firlevelnode = false;
            nodecount = treeView1.Nodes.Count;
            if (nodecount == 0)//当前没有病人被选中
            {
                return;
            }
            else//当前有病人
            {
                #region//判断是否第一层节点
                try
                {

                    parnodeindex = treeView1.SelectedNode.Parent.Index;

                }
                catch
                {
                    firlevelnode = true;//执行到这里，即当前选中节点无父节点，即当前选中节点为第一层的节点，方可结束病人
                }
                #endregion


                if (firlevelnode == true)//若病人树中选中节点为第一层节点，执行这里
                {

                    if (nowpatientblh != "")
                    {
                        using (SqlConnection cn = new SqlConnection())
                        {
                            #region//-------尝试打开连接---------------------------------------
                            cn.ConnectionString = SQLConnect.get(); ;
                            try
                            {
                                cn.Open();
                            }
                            catch
                            {
                                return;
                            }
                            #endregion//--------------------------------------------------------------------------

                            #region//---尝试提交事务，更新jzls.jzzt=9,hzdl.dzzt=4------------------------------------
                            using (SqlTransaction tran = cn.BeginTransaction(IsolationLevel.RepeatableRead))
                            {
                                try
                                {
                                    using (SqlCommand cmd = cn.CreateCommand())
                                    {
                                        cmd.CommandTimeout = 3;
                                        cmd.Transaction = tran;
                                        cmd.CommandText = "update jzls set jssj=@jssj,jzzt='9',ysdm=@ysdm where blh=@blh and ghxh=@ghxh;update hzdl set dzzt='4' where blh=@blh and ghxh=@ghxh";//可能A医生暂挂了一个病人，然后出去了，B医生选出来这个病人，所以要更新ysdm,记到B医生的工作量中

                                        // SqlParameter jzxh,brxm,@blh,@brid,@ksdm,@ysdm,@kssj,@jssj,

                                        SqlParameter blh = new SqlParameter("@blh", SqlDbType.DateTime);
                                        cmd.Parameters.AddWithValue("@blh", nowpatientblh);

                                        SqlParameter ys = new SqlParameter("@ysdm", SqlDbType.DateTime);
                                        cmd.Parameters.AddWithValue("@ysdm", ysdm);

                                        SqlParameter jssj = new SqlParameter("@jssj", SqlDbType.DateTime);
                                        cmd.Parameters.AddWithValue("@jssj", System.DateTime.Now);

                                        SqlParameter ghxh = new SqlParameter("@ghxh", SqlDbType.DateTime);
                                        cmd.Parameters.AddWithValue("@ghxh",nowpatientghxh);

                           

                                        try
                                        {
                                            cmd.ExecuteNonQuery();
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageBox.Show(ex.ToString());
                                        }
                                    }

                                    tran.Commit();//执行事务
                                }

                                catch (Exception ex)
                                {
                                    tran.Rollback();//有错就回滚
                                    MessageBox.Show(ex.ToString());
                                }
                            }
                            #endregion//-------------------------------------------------------------------

                        }
                        treeView1.SelectedNode.Remove();//结束病人，删去该选中节点及其子节点
                        nowpatientblh = ""; nowpatientbrxm = ""; nowpatientbrid = ""; nowpatientbrxb = ""; nowpatientbrxz = ""; nowpatientbrnl = ""; nowpatientgmwy = "";//当前选中病人的信息
                        nowpatientjzxh = "";//清空当前选中病人的信息
                        nowpatientghxh = "";
                        LabPatient.Text = ""; LabSex.Text = ""; LabAge.Text = ""; LabNature.Text = ""; LabGmyw.Text = "";//清空导航栏信息
                    }

                }
                else
                {

                }
            }
 
        }

        private void updateDataBase(string[] sqlarray)//点下一个，或通过输入病历号，选出新病人，对数据库表的更新（hzdl,jzls的修改）
        {
            #region//调用存储过程，取得jzls的最大jzxh,因为要在jzls表中插入一条记录，要用一个单独的连接对象，否则跟下面事务的连接对象会弄混，会报错---
            using (SqlConnection cn2 = new SqlConnection())
            {
                cn2.ConnectionString = SQLConnect.get(); ;
                try
                {
                    cn2.Open();
                }
                catch
                {
                    return;
                }
                SqlCommand cmdgetmax = cn2.CreateCommand();
                cmdgetmax.CommandText = "Jzls_jzxhGetMax";
                cmdgetmax.CommandType = CommandType.StoredProcedure;
                SqlParameter maxjzxh = new SqlParameter("@maxjzxh", SqlDbType.Int);
                maxjzxh.Direction = ParameterDirection.Output;
                cmdgetmax.Parameters.Add(maxjzxh);
                cmdgetmax.ExecuteReader();
                string tempmax = "";
                //
                try
                {
                    tempmax = maxjzxh.Value.ToString();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.ToString());
                }

                if (tempmax == "")//如果就诊历史表里还没有记录，
                    nowpatientjzxh = "1";//则将要插入的记录的就诊序号为1
                else
                    nowpatientjzxh = Convert.ToString(Convert.ToInt32(tempmax) + 1);//将要插入的记录的就诊序号为表中最大jzxh + 1
            }
            #endregion//----------------------------------------------------------------------------------------------

           
            #region//用事务更新hzdl.dzzt表,插入记录到jzls表
            using (SqlConnection cn1 = new SqlConnection(SQLConnect.get()))//用连接对象cn1
            {
               
                #region//--------尝试打开连接----------
                try
                {
                    cn1.Open();
                }
                catch
                {
                    return;
                }
                #endregion//-------------------------------------------------------------------------------------

                #region//取挂号序号
                SqlCommand sc2 = cn1.CreateCommand();
                sc2.CommandText = "select ghxh from hzdl where blh=" + nowpatientblh + " and dzzt='0' and ksdm="+this.ksdm+" and ysdm="+this.ysdm+" and ghsj>=@today";
                sc2.Parameters.AddWithValue("@today", System.DateTime.Today.ToString());//时间一定要用参数话，要不然会报错，识别不了 2012/6/13 0:00:00（有空格！！！！）
                string tempghxh = Convert.ToString(sc2.ExecuteScalar());
                nowpatientghxh = tempghxh;
                #endregion


                #region //----------尝试提交事务,更新hzdl.dzzt表,插入记录到jzls表-----------------------------------------------------
                try
                {

                    using (SqlTransaction tran = cn1.BeginTransaction(IsolationLevel.RepeatableRead))
                    {
                        try
                        {
                            using (SqlCommand cmd = cn1.CreateCommand())
                            {
                                cmd.CommandTimeout = 3;
                                cmd.Transaction = tran;

                                SqlParameter jzxh = new SqlParameter("@jzxh", SqlDbType.NVarChar);
                                cmd.Parameters.AddWithValue("@jzxh", nowpatientjzxh);

                                SqlParameter brxm = new SqlParameter("@brxm", SqlDbType.NVarChar);
                                cmd.Parameters.AddWithValue("@brxm", nowpatientbrxm);

                                SqlParameter blh = new SqlParameter("@blh", SqlDbType.NVarChar);
                                cmd.Parameters.AddWithValue("@blh", nowpatientblh);

                                SqlParameter brid = new SqlParameter("@brid", SqlDbType.NVarChar);
                                cmd.Parameters.AddWithValue("@brid", nowpatientbrid);

                                SqlParameter ksdm = new SqlParameter("@ksdm", SqlDbType.NVarChar);
                                cmd.Parameters.AddWithValue("@ksdm", this.ksdm);

                                SqlParameter ysdm = new SqlParameter("@ysdm", SqlDbType.NVarChar);
                                cmd.Parameters.AddWithValue("@ysdm", this.ysdm);

                                SqlParameter kssj = new SqlParameter("@kssj", SqlDbType.DateTime);
                                cmd.Parameters.AddWithValue("@kssj", System.DateTime.Now);

                                SqlParameter ghxh = new SqlParameter("@ghxh", SqlDbType.NVarChar, 50);
                                cmd.Parameters.AddWithValue("@ghxh", nowpatientghxh);

                                for (int n = 0; n < sqlarray.Length; n++)
                                {
                                    string sqlstr = sqlarray[n].ToString();
                                    if (sqlstr.Trim().Length > 1)
                                    {
                                        cmd.CommandText = sqlstr;
                                        cmd.ExecuteNonQuery();
                                    }
                                }
                            }

                            tran.Commit();
                        }

                        catch (Exception ex)
                        {
                            tran.Rollback(); MessageBox.Show(ex.ToString());
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                //----------------------------------------------------------------------------------------------------
                #endregion


            }
            #endregion
        }

        private void createTree()//点下一个，或从 选病人窗口选出病人 ，或输入病历号选出病人 以后，生成病人树
        {

            //显示导航栏信息
            this.LabAge.Text = nowpatientbrnl;
            this.LabPatient.Text = nowpatientbrxm;
            this.LabSex.Text = nowpatientbrxb;
            this.LabNature.Text = nowpatientbrxz;
            this.LabGmyw.Text = nowpatientgmwy;

            //当前选中病人生成树节点
            TreeNode brxm = new TreeNode(nowpatientbrxm + "@" + System.DateTime.Today.ToShortDateString());
            TreeNode blh = new TreeNode(nowpatientblh);
            TreeNode cfd = new TreeNode("处方单");
            TreeNode jyd = new TreeNode("检验单");
            TreeNode bl = new TreeNode("病历");

            //选出该病人时，查出该病人本次的检验单和处方单并增加到树节点
            //======================================================================
            string sql1 = "select  sqdh from mz_yj01 where jzxh =@jzxh";
            using(SqlConnection cnn= new SqlConnection(SQLConnect.get()))
            {
                cnn.Open();
                SqlCommand mycmd = new SqlCommand(sql1);
                mycmd.Connection = cnn;
                mycmd.Parameters.Add("@jzxh", nowpatientjzxh).Value = nowpatientjzxh;
                SqlDataReader myDr1 = mycmd.ExecuteReader();
                while (myDr1.Read())
                {
                    jyd.Nodes.Add(myDr1[0].ToString().Trim());
                }
                myDr1.Close();
            }

            string sql2 = "select  cfhm from cf01 where jzxh =@jzxh";
            using (SqlConnection cnn1 = new SqlConnection(SQLConnect.get()))
            {
                cnn1.Open();
                SqlCommand mycmd = new SqlCommand(sql2);
                mycmd.Connection = cnn1;
                mycmd.Parameters.Add("@jzxh", nowpatientjzxh).Value = nowpatientjzxh;
                SqlDataReader myDr2 = mycmd.ExecuteReader();
                while (myDr2.Read())
                {
                    cfd.Nodes.Add(myDr2[0].ToString().Trim());
                }
                myDr2.Close();
            }
            //=======================================================================
            
            treeView1.Nodes.Add(brxm);
            brxm.Nodes.Add(blh);
            brxm.Nodes.Add(cfd);
            brxm.Nodes.Add(jyd);
            brxm.Nodes.Add(bl);
            treeView1.SelectedNode = brxm;//让新产生的树节点获得焦点
            treeView1.ExpandAll();
            new PatientInfo(nowpatientblh).ShowDialog();


        }


        //------------------------------------------------------------------------------------------------------------------------

        private void tsBtnClose_Click(object sender, EventArgs e)//退出应用程序
        {
            if (treeView1.Nodes.Count != 0)
            {
                MessageBox.Show("请先处理当前病人！");
            }
            else
                Application.Exit();
        }       

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            modifypwd w_modifypwd = new modifypwd(ygid, ygpwd);
            w_modifypwd.StartPosition = FormStartPosition.CenterScreen;
            w_modifypwd.Location = Cursor.Position;
            w_modifypwd.ShowDialog();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)//常用药物配伍禁忌表查询
        {
            Incompat pwjj = new Incompat();
            pwjj.StartPosition = FormStartPosition.Manual;
            pwjj.Location = Cursor.Position;
            pwjj.ShowDialog();
        }

        private void 常用诊断维护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            zhenduan cyzd = new zhenduan(ysdm, ksdm);
            cyzd.StartPosition = FormStartPosition.Manual; ;
            cyzd.Location = Cursor.Position;
            try
            {
                cyzd.ShowDialog();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        private void 诊断字典ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            zhenduanDictionary zdzd = new zhenduanDictionary(ysdm, ksdm, nowpatientblh);
            zdzd.StartPosition = FormStartPosition.Manual; ;
            zdzd.Location = Cursor.Position;
            zdzd.ShowDialog();
        }

        private void 处方录入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (nowpatientbrid != "")
            {
                cfd cf = new cfd(nowpatientblh, nowpatientbrxm, nowpatientbrid, ygid, ksdm, nowpatientzd,nowpatientjzxh);
                cf.StartPosition = FormStartPosition.Manual;
                cf.Location = Cursor.Position;
                cf.ShowDialog();
                if (cf.DialogResult == DialogResult.Cancel && cfd.cfd_cfhm_qjbl != "")
                {
                    TreeNode tn = new TreeNode(cfd.cfd_cfhm_qjbl);
                    //遍历树节点，找出申请单节点，并增加申请单号
                    foreach (TreeNode node in treeView1.Nodes)
                    {
                        foreach (TreeNode n in node.Nodes)
                        {
                            if (n.Text == "处方单")
                                n.Nodes.Add(tn);
                        }
                    }
                    cfd.cfd_cfhm_qjbl = "";
                }
            }
            else
            {
                MessageBox.Show("请先选择病人！");
            }
        }

        private void 检验单录入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (nowpatientblh == "")
            {
               // new jyd_win("80000503", "2", "", "86").Show();
                MessageBox.Show("请先选择病人", "提示");
                return;
            }
            jyd_win w_jyd_win = new jyd_win(nowpatientblh, ysdm, "", nowpatientjzxh);
            w_jyd_win.StartPosition = FormStartPosition.Manual;
            w_jyd_win.Location = Cursor.Position;
            w_jyd_win.ShowDialog();

            if (w_jyd_win.DialogResult == DialogResult.Cancel && jyd_win.str_sqdh != "")
            {
                TreeNode tn = new TreeNode(jyd_win.str_sqdh);
                //遍历树节点，找出申请单节点，并增加申请单号
                foreach (TreeNode node in treeView1.Nodes)
                {
                    foreach (TreeNode n in node.Nodes)
                    {
                        if (n.Text == "检验单")
                            n.Nodes.Add(tn);
                    }
                }
            }

          
        }

        private void 门诊就诊记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            jzls jz = new jzls(ygid);
            jz.Show();
        }

        private void 添加系统用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(SQLConnect.get()))
                {
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "select ygxm from system_users where ygdm=@ygdm";
                    cmd.Parameters.AddWithValue("@ygdm", ygid);
                    conn.Open();
                    string name = (string)cmd.ExecuteScalar();
                    if (name.Trim() == "管理员")
                    {
                        FrmAddUser fau = new FrmAddUser(ygid);
                        fau.StartPosition = FormStartPosition.Manual;
                        fau.Location = Cursor.Position;
                        fau.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("对不起，你没有权限添加系统用户！");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 工作量统计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gzltj gzl = new gzltj(ygid);
            gzl.ShowDialog();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(treeView1.Nodes.Count!=0)
          
            {
                MessageBox.Show("请先处理当前病人", "提示");

                 e.Cancel=true;
                
            }
            else
           {
                Process[] xc = Process.GetProcesses();//关闭计算器
            try
            {
                foreach (Process xc1 in xc)
                {
                    if (xc1.ProcessName.ToLower().Trim() == "calc")
                    {
                        xc1.Kill();
                        return;
                    }
                }
            }
            catch
            {
                return;
            }
            }

        
        }

        private void 计算器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");//调用系统计算器

        }

        private void 门诊日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mzrz rz = new mzrz(ygid,ksdm,nowpatientjzxh);
            rz.StartPosition = FormStartPosition.Manual;
            rz.Location = Cursor.Position;
            rz.ShowDialog();
        }

        private void 查询检验单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Queryjyd(nowpatientbrid).ShowDialog();
        }

        private void tsTxtCaseHistory_Click(object sender, EventArgs e)
        {

        }
    }

}